package com.itheima.mysecurity;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        try {
            if (e.getMessage().equals("accountFreeze")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                String result = JSON.toJSONString(new Result(false, "您的账号已被冻结,请联系系统管理员进行解密"));
                httpServletResponse.getWriter().print(result);
            }
            if ( e.getMessage().equals("userNull")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                String result = JSON.toJSONString(new Result(false, "您输入的同户名不存在"));
                httpServletResponse.getWriter().print(result);
            }
            if (e.getMessage().equals("Bad credentials")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                String result = JSON.toJSONString(new Result(false, "您输入的密码有误请重新输入"));
                httpServletResponse.getWriter().print(result);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
